package com.tma.customlistview;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.tma.customlistview.xml.MusicParser;
import com.tma.customlistview.xml.Song;

public class CustomListView extends Activity {
    private static final String TAG = "CustomListView";
    private ListView mListView;
    private SongsAdapter mAdapter;
    private List<Song> mSongs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_list_view);

        mSongs = new ArrayList<Song>();
        mListView = (ListView) findViewById(R.id.list);
        mAdapter = new SongsAdapter(this, mSongs);
        mListView.setAdapter(mAdapter);

        // Click event for single list row
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "Clicked item " + position);
            }
        });

        new LoadSongsTask().execute();
    }

    private class LoadSongsTask extends AsyncTask<Void, Void, List<Song>> {
        private ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(CustomListView.this, "", "Loading...");
        }

        @Override
        protected List<Song> doInBackground(Void... params) {
            MusicParser parser = new MusicParser();
            List<Song> songs = null;
            try {
                InputStream stream = getResources().openRawResource(R.raw.music);
                songs = parser.parse(stream);
            } catch (XmlPullParserException e) {
                Log.e(TAG, e.getMessage(), e);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
            return songs;
        }

        @Override
        protected void onPostExecute(List<Song> result) {
            progressDialog.cancel();
            if (result != null) {
                mSongs.addAll(result);
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
